package com.xxmw.transaction.resolver;

import com.xxmw.transaction.common.annotation.LoginUser;
import com.xxmw.transaction.common.utils.Assert;
import com.xxmw.transaction.interceptor.AuthorizationInterceptor;
import com.xxmw.transaction.model.app.User;
import com.xxmw.transaction.service.app.UserService;
import com.xxmw.transaction.service.app.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.reflect.Field;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 *
 */
@Slf4j
@Component
public class LoginUserHandlerMethodArgumentResolver  implements HandlerMethodArgumentResolver{

    @Autowired
    private UserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        LoginUser loginUser = parameter.getParameterAnnotation(LoginUser.class);
        //获取用户ID
        User user = (User) request.getAttribute(AuthorizationInterceptor.STAFF_KEY, RequestAttributes.SCOPE_REQUEST);
        if(Assert.isNullOrEmpty(user)){
            return null;
        }
        //获取用户信息
        user = userService.getById(user.getId());
        if (Assert.isNotNullOrEmpty(loginUser.value())) {
            Field field = user.getClass().getDeclaredField(loginUser.value());
            if (Assert.isNotNullOrEmpty(field)) {
                field.setAccessible(true);
            }
            Object params = field.get(user);
            return params;
        }
        return user;
    }
}
